<template>
  <div class="admin-dashboard">
    <!-- 顶部欢迎区域 -->
    <div class="welcome-banner">
      <div class="welcome-content">
        <h1>您好，{{ userName || '管理员' }}！</h1>
        <p>欢迎使用流浪动物救助系统管理后台</p>
      </div>
    </div>

    <!-- 服务器详细信息卡片 -->
    <el-card shadow="hover" class="server-detail-card">
      <template #header>
        <div class="card-header">
          <el-icon class="header-icon"><Monitor /></el-icon>
          <span>服务器详细信息</span>
          <el-button 
            type="text" 
            size="small" 
            @click="loadServerResourceInfo"
            :loading="serverResourceLoading"
            style="margin-left: auto;"
          >
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </template>
      <div class="server-detail-content">
        <el-row :gutter="20">
          <!-- 服务器CPU信息 -->
          <el-col :span="12">
            <div class="resource-item">
              <div class="resource-header">
                <div class="resource-title">
                  <el-icon class="resource-icon"><DataAnalysis /></el-icon>
                  <span>服务器 CPU 信息</span>
                </div>
                <div class="resource-value" v-if="serverResource.cpuUsage >= 0">{{ serverResource.cpuUsage }}%</div>
                <div class="resource-value" v-else style="color: #909399;">暂不可用</div>
              </div>
              <el-progress 
                v-if="serverResource.cpuUsage >= 0"
                :percentage="serverResource.cpuUsage" 
                :color="getProgressColor(serverResource.cpuUsage)"
                :stroke-width="20"
                :show-text="false"
              />
              <div v-else class="progress-placeholder">
                <el-alert type="info" :closable="false" show-icon>
                  CPU使用率暂不可用（后端返回-1）
                </el-alert>
              </div>
              <div class="resource-details">
                <span>核心数: {{ serverResource.cpuCores !== undefined && serverResource.cpuCores !== null ? serverResource.cpuCores : '未知' }}</span>
                <span>处理器: {{ serverResource.cpuModel || '未知' }}</span>
              </div>
            </div>
          </el-col>
          
          <!-- 服务器内存使用率 -->
          <el-col :span="12">
            <div class="resource-item">
              <div class="resource-header">
                <div class="resource-title">
                  <el-icon class="resource-icon"><DataAnalysis /></el-icon>
                  <span>服务器内存使用率</span>
                </div>
                <div class="resource-value">{{ serverResource.memoryUsage }}</div>
              </div>
              <el-progress 
                :percentage="serverResource.memoryUsageNum || 0" 
                :color="getProgressColor(serverResource.memoryUsageNum)"
                :stroke-width="20"
                :show-text="false"
              />
              <div class="resource-details">
                <span>已用: {{ formatBytes(serverResource.memoryUsed) }}</span>
                <span>总计: {{ formatBytes(serverResource.memoryTotal) }}</span>
              </div>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20" style="margin-top: 20px;">
          <!-- 磁盘使用情况 -->
          <el-col :span="12">
            <div class="resource-item">
              <div class="resource-header">
                <div class="resource-title">
                  <el-icon class="resource-icon"><Files /></el-icon>
                  <span>服务器磁盘使用情况</span>
                </div>
              </div>
              <div class="disk-info" v-if="serverResource.diskUsage && serverResource.diskUsage.trim()">
                <template v-if="parsedDiskDrives.length > 0">
                  <div 
                    v-for="(drive, index) in parsedDiskDrives" 
                    :key="index"
                    class="disk-drive"
                  >
                    <div class="disk-header">
                      <span class="disk-name">{{ drive.name }}</span>
                      <span class="disk-usage">{{ drive.usage }}%</span>
                    </div>
                    <el-progress 
                      :percentage="drive.usage" 
                      :color="getProgressColor(drive.usage)"
                      :stroke-width="12"
                      :show-text="false"
                    />
                    <div class="disk-details">
                      <span>总计: {{ drive.total }}</span>
                      <span>可用: {{ drive.free }}</span>
                    </div>
                  </div>
                </template>
                <el-alert v-else type="warning" :closable="false" show-icon>
                  磁盘信息格式解析失败
                </el-alert>
              </div>
              <div v-else class="disk-info">
                <el-alert type="info" :closable="false" show-icon>
                  磁盘信息暂不可用
                </el-alert>
              </div>
            </div>
          </el-col>
          
          <!-- 系统信息 -->
          <el-col :span="12">
            <div class="resource-item">
              <div class="resource-header">
                <div class="resource-title">
                  <el-icon class="resource-icon"><Monitor /></el-icon>
                  <span>系统信息</span>
                </div>
              </div>
              <div class="system-details">
                <div class="detail-row">
                  <span class="detail-label">操作系统:</span>
                  <span class="detail-value">{{ serverResource.osName || serverInfo.os || '未知' }}</span>
                </div>
                <div class="detail-row">
                  <span class="detail-label">系统版本:</span>
                  <span class="detail-value">{{ serverResource.osVersion || '未知' }}</span>
                </div>
                <div class="detail-row">
                  <span class="detail-label">运行时间:</span>
                  <span class="detail-value">{{ formatUptime(serverResource.uptime) }}</span>
                </div>
                <div class="detail-row">
                  <span class="detail-label">服务器名称:</span>
                  <span class="detail-value">{{ serverResource.hostname || '未知' }}</span>
                </div>
                <div class="detail-row">
                  <span class="detail-label">IP地址:</span>
                  <span class="detail-value">{{ serverResource.ipAddress || '未知' }}</span>
                </div>
                <div class="detail-row">
                  <span class="detail-label">Java版本:</span>
                  <span class="detail-value">{{ serverResource.javaVersion || '未知' }}</span>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>

        <!-- JVM信息 -->
        <el-row :gutter="20" style="margin-top: 20px;" v-if="serverResource.jvmTotalMemory">
          <el-col :span="24">
            <div class="resource-item">
              <div class="resource-header">
                <div class="resource-title">
                  <el-icon class="resource-icon"><DataAnalysis /></el-icon>
                  <span>JVM 内存信息</span>
                </div>
              </div>
              <div class="jvm-info">
                <el-row :gutter="20">
                  <el-col :span="6">
                    <div class="jvm-item">
                      <div class="jvm-label">堆内存使用率</div>
                      <div class="jvm-value">{{ serverResource.jvmMemoryUsage || 0 }}%</div>
                      <el-progress 
                        :percentage="parseFloat(serverResource.jvmMemoryUsage || 0)" 
                        :color="getProgressColor(serverResource.jvmMemoryUsage)"
                        :stroke-width="12"
                      />
                      <div class="jvm-details">
                        <span>已用: {{ formatBytes(serverResource.jvmUsedMemory) }}</span>
                        <span>最大: {{ formatBytes(serverResource.jvmMaxMemory) }}</span>
                      </div>
                    </div>
                  </el-col>
                  <el-col :span="6">
                    <div class="jvm-item">
                      <div class="jvm-label">堆内存总量</div>
                      <div class="jvm-value">{{ formatBytes(serverResource.jvmTotalMemory) }}</div>
                    </div>
                  </el-col>
                  <el-col :span="6">
                    <div class="jvm-item">
                      <div class="jvm-label">已使用堆内存</div>
                      <div class="jvm-value">{{ formatBytes(serverResource.jvmUsedMemory) }}</div>
                    </div>
                  </el-col>
                  <el-col :span="6">
                    <div class="jvm-item">
                      <div class="jvm-label">最大堆内存</div>
                      <div class="jvm-value">{{ formatBytes(serverResource.jvmMaxMemory) }}</div>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </div>
          </el-col>
        </el-row>

        <!-- 网络信息 -->
        <el-row :gutter="20" style="margin-top: 20px;" v-if="serverResource.networkInfo">
          <el-col :span="24">
            <div class="resource-item">
              <div class="resource-header">
                <div class="resource-title">
                  <el-icon class="resource-icon"><Message /></el-icon>
                  <span>网络信息</span>
                </div>
              </div>
              <div class="network-info">
                <el-row :gutter="20">
                  <el-col :span="8" v-for="(net, index) in serverResource.networkInfo" :key="index">
                    <div class="network-item">
                      <div class="network-name">{{ net.name || '未知' }}</div>
                      <div class="network-details">
                        <div>IP: {{ net.ip || '未知' }}</div>
                        <div>状态: <span :class="(net.status && net.status.toUpperCase() === 'UP') ? 'status-up' : 'status-down'">{{ net.status || '未知' }}</span></div>
                      </div>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 本机系统信息卡片 -->
    <el-card shadow="hover" class="system-info-card">
      <template #header>
        <div class="card-header">
          <el-icon class="header-icon"><Monitor /></el-icon>
          <span>本机系统信息</span>
        </div>
      </template>
      <div class="system-info-content">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="info-item info-item-blue">
              <el-icon class="info-icon"><Monitor /></el-icon>
              <div class="info-content">
                <div class="info-label">操作系统</div>
                <div class="info-value">{{ serverInfo.os || '未知' }}</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item info-item-green">
              <el-icon class="info-icon"><DataAnalysis /></el-icon>
              <div class="info-content">
                <div class="info-label">浏览器</div>
                <div class="info-value">{{ serverInfo.browser || '未知' }}</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item info-item-orange">
              <el-icon class="info-icon"><Clock /></el-icon>
              <div class="info-content">
                <div class="info-label">当前时间</div>
                <div class="info-value">{{ currentTime }}</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item info-item-purple">
              <el-icon class="info-icon"><Message /></el-icon>
              <div class="info-content">
                <div class="info-label">屏幕分辨率</div>
                <div class="info-value">{{ serverInfo.screen || '未知' }}</div>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="6">
            <div class="info-item info-item-cyan">
              <el-icon class="info-icon"><DataAnalysis /></el-icon>
              <div class="info-content">
                <div class="info-label">内存信息</div>
                <div class="info-value">{{ serverInfo.memory || '未知' }}</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item info-item-pink">
              <el-icon class="info-icon"><Monitor /></el-icon>
              <div class="info-content">
                <div class="info-label">CPU核心数</div>
                <div class="info-value">{{ serverInfo.cpuCores || '未知' }}</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item info-item-indigo">
              <el-icon class="info-icon"><Message /></el-icon>
              <div class="info-content">
                <div class="info-label">语言</div>
                <div class="info-value">{{ serverInfo.language || '未知' }}</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item info-item-teal">
              <el-icon class="info-icon"><Clock /></el-icon>
              <div class="info-content">
                <div class="info-label">时区</div>
                <div class="info-value">{{ serverInfo.timezone || '未知' }}</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 快速操作 -->
    <el-card shadow="hover" class="quick-actions-card">
      <template #header>
        <div class="card-header">
          <el-icon class="header-icon"><House /></el-icon>
          <span>快速操作</span>
        </div>
      </template>
      <div class="quick-actions">
        <el-row :gutter="20">
          <el-col :span="4" v-for="item in quickActions" :key="item.path">
            <div class="action-item" @click="navigateTo(item.path)">
              <el-icon class="action-icon" :size="32" :color="item.color">
                <component :is="item.icon" />
              </el-icon>
              <div class="action-title">{{ item.title }}</div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 统计图表区域 -->
    <div class="charts-section">
      <el-row :gutter="20">
        <!-- 用户状态统计 -->
        <el-col :span="12">
          <el-card shadow="hover" class="chart-wrapper">
            <template #header>
              <div class="chart-header">
                <span class="chart-title">用户状态统计</span>
                <el-radio-group v-model="chartTypes.userStatus" size="small" @change="updateUserStatusChart">
                  <el-radio-button label="pie">饼图</el-radio-button>
                  <el-radio-button label="line">折线图</el-radio-button>
                  <el-radio-button label="bar">柱状图</el-radio-button>
                </el-radio-group>
              </div>
            </template>
            <div ref="userStatusChart" class="chart-container"></div>
          </el-card>
        </el-col>

        <!-- 动物状态统计 -->
        <el-col :span="12">
          <el-card shadow="hover" class="chart-wrapper">
            <template #header>
              <div class="chart-header">
                <span class="chart-title">动物状态统计</span>
                <el-radio-group v-model="chartTypes.animalStatus" size="small" @change="updateAnimalStatusChart">
                  <el-radio-button label="pie">饼图</el-radio-button>
                  <el-radio-button label="line">折线图</el-radio-button>
                  <el-radio-button label="bar">柱状图</el-radio-button>
                </el-radio-group>
              </div>
            </template>
            <div ref="animalStatusChart" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px;">
        <!-- 救助记录状态统计 -->
        <el-col :span="12">
          <el-card shadow="hover" class="chart-wrapper">
            <template #header>
              <div class="chart-header">
                <span class="chart-title">救助记录状态统计</span>
                <el-radio-group v-model="chartTypes.rescueInfo" size="small" @change="updateRescueInfoStatusChart">
                  <el-radio-button label="pie">饼图</el-radio-button>
                  <el-radio-button label="line">折线图</el-radio-button>
                  <el-radio-button label="bar">柱状图</el-radio-button>
                </el-radio-group>
              </div>
            </template>
            <div ref="rescueInfoStatusChart" class="chart-container"></div>
          </el-card>
        </el-col>

        <!-- 领养申请状态统计 -->
        <el-col :span="12">
          <el-card shadow="hover" class="chart-wrapper">
            <template #header>
              <div class="chart-header">
                <span class="chart-title">领养申请状态统计</span>
                <el-radio-group v-model="chartTypes.adoption" size="small" @change="updateAdoptionStatusChart">
                  <el-radio-button label="pie">饼图</el-radio-button>
                  <el-radio-button label="line">折线图</el-radio-button>
                  <el-radio-button label="bar">柱状图</el-radio-button>
                </el-radio-group>
              </div>
            </template>
            <div ref="adoptionStatusChart" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import * as echarts from 'echarts';
import { House, DocumentChecked, Bell, Message, Files, Monitor, DataAnalysis, Clock, Refresh } from '@element-plus/icons-vue';

export default {
  name: "AdminDashboard",
  components: {
    House,
    DocumentChecked,
    Bell,
    Message,
    Files,
    Monitor,
    DataAnalysis,
    Clock,
    Refresh
  },
  data() {
    return {
      userName: '',
      currentTime: '',
      timeInterval: null,
      serverInfo: {
        os: '',
        browser: '',
        screen: '',
        memory: '',
        cpuCores: '',
        language: '',
        timezone: ''
      },
      chartTypes: {
        userStatus: 'pie',
        animalStatus: 'pie',
        rescueInfo: 'pie',
        adoption: 'pie'
      },
      serverResource: {
        cpuUsage: -1,
        cpuCores: 0,
        cpuModel: '',
        memoryUsage: '0%',
        memoryUsed: 0,
        memoryTotal: 0,
        diskUsage: '',
        diskUsed: 0,
        diskTotal: 0,
        osName: '',
        osVersion: '',
        uptime: 0,
        hostname: '',
        ipAddress: '',
        javaVersion: '',
        jvmTotalMemory: 0,
        jvmUsedMemory: 0,
        jvmMaxMemory: 0,
        jvmMemoryUsage: 0,
        networkInfo: []
      },
      clientResource: {
        cpuCores: 0,
        hardwareConcurrency: 0,
        memory: '',
        deviceMemory: '',
        memoryUsed: 0,
        memoryTotal: 0,
        jsHeapSize: ''
      },
      serverResourceLoading: false,
      serverResourceInterval: null,
      userStatusData: [],
      animalStatusData: {},
      rescueInfoStatusData: {},
      adoptionStatusData: {},
      quickActions: [
        {
          path: '/admin/adoptionReview',
          title: '领养审核',
          desc: '审核用户的领养申请',
          icon: DocumentChecked,
          color: '#409EFF'
        },
        {
          path: '/admin/announcement',
          title: '公告管理',
          desc: '管理系统公告',
          icon: Bell,
          color: '#E6A23C'
        },
        {
          path: '/admin/news',
          title: '新闻管理',
          desc: '管理系统新闻',
          icon: Message,
          color: '#67C23A'
        },
        {
          path: '/admin/animalManage',
          title: '动物档案',
          desc: '管理系统动物信息',
          icon: Files,
          color: '#909399'
        },
        {
          path: '/admin/healthRecordManage',
          title: '健康档案',
          desc: '管理系统健康档案',
          icon: Files,
          color: '#67C23A'
        },
        {
          path: '/admin/rescueStoryManage',
          title: '故事档案',
          desc: '管理系统救助故事',
          icon: Files,
          color: '#E6A23C'
        }
      ]
    };
  },
  computed: {
    parsedDiskDrives() {
      if (!this.serverResource.diskUsage || typeof this.serverResource.diskUsage !== 'string') {
        return [];
      }
      return this.parseDiskInfo(this.serverResource.diskUsage);
    }
  },
  mounted() {
    this.loadUserInfo();
    this.loadServerInfo();
    this.loadClientResourceInfo();
    this.loadServerResourceInfo();
    this.updateTime();
    this.timeInterval = setInterval(() => {
      this.updateTime();
    }, 1000);
    // 每30秒自动刷新服务器资源信息
    this.serverResourceInterval = setInterval(() => {
      this.loadServerResourceInfo();
    }, 30000);
    this.fetchStatistics();
  },
  beforeUnmount() {
    if (this.timeInterval) {
      clearInterval(this.timeInterval);
    }
    if (this.serverResourceInterval) {
      clearInterval(this.serverResourceInterval);
    }
  },
  methods: {
    updateTime() {
      const now = new Date();
      this.currentTime = now.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    },
    async loadUserInfo() {
      const userId = localStorage.getItem('userId');
      if (!userId) return;

      try {
        const res = await axios.get(`http://localhost:8080/api/user/${userId}`);
        if (res.data.code === 200) {
          const user = res.data.data;
          this.userName = user.nickname || user.username || '管理员';
        }
      } catch (error) {
        console.error('加载用户信息失败:', error);
      }
    },
    navigateTo(path) {
      this.$router.push(path);
    },
    async loadServerResourceInfo() {
      this.serverResourceLoading = true;
      try {
        const res = await axios.get('http://localhost:8080/api/admin/server/resource');
        console.log('服务器资源API完整响应:', res);
        console.log('服务器资源API响应数据:', res.data);
        
        // 处理不同的响应格式
        let data = {};
        if (res.data && res.data.code === 200) {
          // 标准格式: {code: 200, data: {...}}
          data = res.data.data || {};
        } else if (res.data && (res.data.cpuUsage !== undefined || res.data.cpuCores !== undefined)) {
          // 直接返回数据对象格式（后端直接返回数据，没有包装在data中）
          data = res.data;
        } else {
          console.error('无法识别的响应格式:', res.data);
          return;
        }
        
        console.log('解析的服务器数据:', data);
        
        // 解析内存使用率（可能是字符串 "3.07%"）
        let memoryUsageNum = 0;
        if (typeof data.memoryUsage === 'string') {
          memoryUsageNum = parseFloat(data.memoryUsage.replace('%', '')) || 0;
        } else {
          memoryUsageNum = data.memoryUsage || 0;
        }
        
        // 计算JVM内存使用率
        const jvmMemoryUsage = data.jvmMaxMemory && data.jvmMaxMemory > 0 
          ? ((data.jvmUsedMemory || 0) / data.jvmMaxMemory * 100).toFixed(2) 
          : 0;
        
        // 直接使用后端返回的数据，严格判断 undefined 和 null，避免覆盖真实数据（包括0值）
        // 使用 Object.assign 确保响应式更新
        Object.assign(this.serverResource, {
          cpuUsage: data.hasOwnProperty('cpuUsage') ? data.cpuUsage : -1,
          cpuCores: data.hasOwnProperty('cpuCores') ? data.cpuCores : 0,
          cpuModel: (data.hasOwnProperty('cpuModel') && data.cpuModel !== null && data.cpuModel !== '') ? data.cpuModel : '未知',
          memoryUsage: data.hasOwnProperty('memoryUsage') ? data.memoryUsage : '0%',
          memoryUsageNum: memoryUsageNum,
          memoryUsed: data.hasOwnProperty('memoryUsed') ? data.memoryUsed : 0,
          memoryTotal: data.hasOwnProperty('memoryTotal') ? data.memoryTotal : 0,
          diskUsage: data.hasOwnProperty('diskUsage') ? (data.diskUsage || '') : '',
          diskUsed: data.hasOwnProperty('diskUsed') ? data.diskUsed : 0,
          diskTotal: data.hasOwnProperty('diskTotal') ? data.diskTotal : 0,
          osName: (data.hasOwnProperty('osName') && data.osName !== null && data.osName !== '') ? data.osName : '',
          osVersion: (data.hasOwnProperty('osVersion') && data.osVersion !== null && data.osVersion !== '') ? data.osVersion : '',
          uptime: data.hasOwnProperty('uptime') ? data.uptime : 0,
          hostname: (data.hasOwnProperty('hostname') && data.hostname !== null && data.hostname !== '') ? data.hostname : '',
          ipAddress: (data.hasOwnProperty('ipAddress') && data.ipAddress !== null && data.ipAddress !== '') ? data.ipAddress : '',
          javaVersion: (data.hasOwnProperty('javaVersion') && data.javaVersion !== null && data.javaVersion !== '') ? data.javaVersion : '',
          jvmTotalMemory: data.hasOwnProperty('jvmTotalMemory') ? data.jvmTotalMemory : 0,
          jvmUsedMemory: data.hasOwnProperty('jvmUsedMemory') ? data.jvmUsedMemory : 0,
          jvmMaxMemory: data.hasOwnProperty('jvmMaxMemory') ? data.jvmMaxMemory : 0,
          jvmMemoryUsage: parseFloat(jvmMemoryUsage),
          networkInfo: Array.isArray(data.networkInfo) ? data.networkInfo : []
        });
        
        console.log('赋值后的serverResource:', this.serverResource);
        console.log('CPU核心数:', this.serverResource.cpuCores);
        console.log('内存使用率:', this.serverResource.memoryUsage);
        console.log('操作系统:', this.serverResource.osName);
      } catch (error) {
        console.error('获取服务器资源信息失败:', error);
        console.error('错误详情:', error.response);
      } finally {
        this.serverResourceLoading = false;
      }
    },
    loadClientResourceInfo() {
      // 获取客户端CPU核心数
      const hardwareConcurrency = navigator.hardwareConcurrency || 0;
      
      // 获取设备内存
      const deviceMemory = navigator.deviceMemory ? `${navigator.deviceMemory} GB` : '未知';
      
      // 获取JS堆内存信息
      let jsHeapSize = '未知';
      let memoryUsed = 0;
      let memoryTotal = 0;
      if (performance.memory) {
        memoryUsed = performance.memory.used;
        memoryTotal = performance.memory.total;
        const usedMB = (memoryUsed / 1024 / 1024).toFixed(2);
        const totalMB = (memoryTotal / 1024 / 1024).toFixed(2);
        jsHeapSize = `${usedMB} MB / ${totalMB} MB`;
      }
      
      this.clientResource = {
        cpuCores: hardwareConcurrency,
        hardwareConcurrency: hardwareConcurrency,
        memory: deviceMemory,
        deviceMemory: deviceMemory,
        memoryUsed: memoryUsed,
        memoryTotal: memoryTotal,
        jsHeapSize: jsHeapSize
      };
    },
    formatBytes(bytes) {
      if (!bytes || bytes === 0) return '0 B';
      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
    },
    getProgressColor(usage) {
      const value = parseFloat(usage || 0);
      if (value < 0) return '#909399';
      if (value < 50) return '#67c23a';
      if (value < 80) return '#e6a23c';
      return '#f56c6c';
    },
    parseDiskInfo(diskUsageStr) {
      if (!diskUsageStr || typeof diskUsageStr !== 'string') {
        console.log('磁盘信息为空或不是字符串:', diskUsageStr);
        return [];
      }
      
      console.log('解析磁盘信息:', diskUsageStr);
      const drives = [];
      const lines = diskUsageStr.split('\n').filter(line => line.trim());
      console.log('分割后的行:', lines);
      
      lines.forEach(line => {
        // 解析格式: "Drive: C:\, Total: 225 GB, Free: 38 GB"
        const driveMatch = line.match(/Drive:\s*([^,]+),\s*Total:\s*([^,]+),\s*Free:\s*(.+)/);
        if (driveMatch) {
          const name = driveMatch[1].trim();
          const total = driveMatch[2].trim();
          const free = driveMatch[3].trim();
          
          // 计算使用率
          const totalGB = parseFloat(total);
          const freeGB = parseFloat(free);
          const usedGB = totalGB - freeGB;
          const usage = totalGB > 0 ? ((usedGB / totalGB) * 100).toFixed(1) : 0;
          
          drives.push({
            name: name,
            total: total,
            free: free,
            used: `${usedGB.toFixed(1)} GB`,
            usage: parseFloat(usage)
          });
        } else {
          console.log('无法解析的行:', line);
        }
      });
      
      console.log('解析后的驱动器:', drives);
      return drives;
    },
    formatUptime(seconds) {
      if (!seconds || seconds === 0) return '未知';
      const days = Math.floor(seconds / 86400);
      const hours = Math.floor((seconds % 86400) / 3600);
      const minutes = Math.floor((seconds % 3600) / 60);
      
      if (days > 0) {
        return `${days}天 ${hours}小时 ${minutes}分钟`;
      } else if (hours > 0) {
        return `${hours}小时 ${minutes}分钟`;
      } else {
        return `${minutes}分钟`;
      }
    },
    loadServerInfo() {
      // 获取本机系统信息
      const ua = navigator.userAgent;
      
      // 检测操作系统
      let os = 'Unknown';
      if (ua.indexOf('Win') > -1) os = 'Windows';
      else if (ua.indexOf('Mac') > -1) os = 'macOS';
      else if (ua.indexOf('Linux') > -1) os = 'Linux';
      else if (ua.indexOf('Android') > -1) os = 'Android';
      else if (ua.indexOf('iOS') > -1) os = 'iOS';
      
      // 检测浏览器
      let browser = 'Unknown';
      if (ua.indexOf('Chrome') > -1 && ua.indexOf('Edg') === -1) browser = 'Chrome';
      else if (ua.indexOf('Firefox') > -1) browser = 'Firefox';
      else if (ua.indexOf('Safari') > -1 && ua.indexOf('Chrome') === -1) browser = 'Safari';
      else if (ua.indexOf('Edg') > -1) browser = 'Edge';
      else if (ua.indexOf('Opera') > -1 || ua.indexOf('OPR') > -1) browser = 'Opera';
      
      // 获取屏幕分辨率
      const screen = `${window.screen.width} × ${window.screen.height}`;
      
      // 获取内存信息（如果可用）
      let memory = '未知';
      if (navigator.deviceMemory) {
        memory = `${navigator.deviceMemory} GB`;
      } else if (performance.memory) {
        const total = (performance.memory.total / 1024 / 1024 / 1024).toFixed(2);
        const used = (performance.memory.used / 1024 / 1024 / 1024).toFixed(2);
        memory = `已用 ${used} GB / 总计 ${total} GB`;
      }
      
      // 获取CPU核心数
      const cpuCores = navigator.hardwareConcurrency || '未知';
      
      // 获取语言
      const language = navigator.language || navigator.userLanguage || '未知';
      
      // 获取时区
      const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || '未知';
      
      this.serverInfo = {
        os: os,
        browser: browser,
        screen: screen,
        memory: memory,
        cpuCores: cpuCores.toString(),
        language: language,
        timezone: timezone
      };
    },
    async fetchStatistics() {
      try {
        // 用户状态统计 - 返回格式: [{count: 4, status: 1}]
        const userResponse = await axios.get('http://localhost:8080/api/admin/statistics/userStatusCount');
        if (userResponse.data.code === 200) {
          this.userStatusData = userResponse.data.data || [];
        }

        // 动物状态统计
        const animalResponse = await axios.get('http://localhost:8080/api/admin/statistics/animalStatusCount');
        if (animalResponse.data.code === 200) {
          this.animalStatusData = animalResponse.data.data || {};
        }

        // 救助记录状态统计
        const rescueInfoResponse = await axios.get('http://localhost:8080/api/admin/statistics/rescueInfoStatusCount');
        if (rescueInfoResponse.data.code === 200) {
          this.rescueInfoStatusData = rescueInfoResponse.data.data || {};
        }

        // 领养申请状态统计 - 返回格式: {审核通过: 1, 驳回: 1, 待审核: 0}
        const adoptionResponse = await axios.get('http://localhost:8080/api/admin/statistics/adoptionStatusCount');
        if (adoptionResponse.data.code === 200) {
          this.adoptionStatusData = adoptionResponse.data.data || {};
        }

        this.$nextTick(() => {
          this.updateCharts();
        });
      } catch (error) {
        console.error('获取统计数据失败:', error);
      }
    },
    updateCharts() {
      this.updateUserStatusChart();
      this.updateAnimalStatusChart();
      this.updateRescueInfoStatusChart();
      this.updateAdoptionStatusChart();
    },
    getChartOption(type, title, data, colors) {
      const commonOption = {
        title: { 
          text: title,
          left: 'center',
          textStyle: { fontSize: 16, fontWeight: 'bold' }
        },
        tooltip: { 
          trigger: type === 'pie' ? 'item' : 'axis',
          formatter: type === 'pie' ? '{a} <br/>{b}: {c} ({d}%)' : '{b}: {c}'
        }
      };

      if (type === 'pie') {
        return {
          ...commonOption,
          legend: {
            orient: 'vertical',
            left: 'left',
            top: 'middle'
          },
          series: [{
            name: title,
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              formatter: '{b}: {c}\n({d}%)'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 16,
                fontWeight: 'bold'
              }
            },
            data: data.map((item, index) => ({
              ...item,
              itemStyle: { color: colors[index] || item.itemStyle?.color }
            }))
          }]
        };
      } else if (type === 'line') {
        return {
          ...commonOption,
          xAxis: {
            type: 'category',
            data: data.map(item => item.name)
          },
          yAxis: {
            type: 'value'
          },
          series: [{
            name: title,
            type: 'line',
            data: data.map(item => item.value),
            smooth: true,
            itemStyle: {
              color: colors[0] || '#409EFF'
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: colors[0] || '#409EFF'
                }, {
                  offset: 1, color: 'rgba(64, 158, 255, 0.1)'
                }]
              }
            }
          }]
        };
      } else if (type === 'bar') {
        return {
          ...commonOption,
          xAxis: {
            type: 'category',
            data: data.map(item => item.name)
          },
          yAxis: {
            type: 'value'
          },
          series: [{
            name: title,
            type: 'bar',
            data: data.map((item, index) => ({
              value: item.value,
              itemStyle: { color: colors[index] || item.itemStyle?.color }
            })),
            barWidth: '60%'
          }]
        };
      }
      return commonOption;
    },
    updateUserStatusChart() {
      if (!this.$refs.userStatusChart) return;
      try {
        const chart = echarts.init(this.$refs.userStatusChart);
        
        // 解析用户状态数据: [{count: 4, status: 1}]
        let normalCount = 0;
        let disabledCount = 0;
        
        if (Array.isArray(this.userStatusData)) {
          this.userStatusData.forEach(item => {
            if (item.status === 1) {
              normalCount = item.count || 0;
            } else if (item.status === 0) {
              disabledCount = item.count || 0;
            }
          });
        }
        
        const data = [
          { name: '正常', value: normalCount },
          { name: '禁用', value: disabledCount }
        ];
        const colors = ['#67C23A', '#F56C6C'];
        
        chart.setOption(this.getChartOption(this.chartTypes.userStatus, '用户状态统计', data, colors));
      } catch (error) {
        console.error('初始化用户状态图表失败:', error);
      }
    },
    updateAnimalStatusChart() {
      if (!this.$refs.animalStatusChart) return;
      try {
        const chart = echarts.init(this.$refs.animalStatusChart);
        const data = [
          { name: '待领养', value: this.animalStatusData[0] || 0 },
          { name: '已领养', value: this.animalStatusData[1] || 0 },
          { name: '审核中', value: this.animalStatusData[3] || 0 }
        ];
        const colors = ['#409EFF', '#67C23A', '#E6A23C'];
        chart.setOption(this.getChartOption(this.chartTypes.animalStatus, '动物状态统计', data, colors));
      } catch (error) {
        console.error('初始化动物状态图表失败:', error);
      }
    },
    updateRescueInfoStatusChart() {
      if (!this.$refs.rescueInfoStatusChart) return;
      try {
        const chart = echarts.init(this.$refs.rescueInfoStatusChart);
        const data = [
          { name: '进行中', value: this.rescueInfoStatusData[1] || 0 },
          { name: '已完成', value: this.rescueInfoStatusData[2] || 0 },
          { name: '已驳回', value: this.rescueInfoStatusData[3] || 0 }
        ];
        const colors = ['#409EFF', '#67C23A', '#F56C6C'];
        chart.setOption(this.getChartOption(this.chartTypes.rescueInfo, '救助记录状态统计', data, colors));
      } catch (error) {
        console.error('初始化救助记录状态图表失败:', error);
      }
    },
    updateAdoptionStatusChart() {
      if (!this.$refs.adoptionStatusChart) return;
      try {
        const chart = echarts.init(this.$refs.adoptionStatusChart);
        
        // 解析领养状态数据: {审核通过: 1, 驳回: 1, 待审核: 0}
        const adoptionData = [];
        if (this.adoptionStatusData && typeof this.adoptionStatusData === 'object') {
          if (this.adoptionStatusData['待审核'] !== undefined) {
            adoptionData.push({ 
              name: '待审核', 
              value: this.adoptionStatusData['待审核'] || 0
            });
          }
          if (this.adoptionStatusData['审核通过'] !== undefined) {
            adoptionData.push({ 
              name: '审核通过', 
              value: this.adoptionStatusData['审核通过'] || 0
            });
          }
          if (this.adoptionStatusData['驳回'] !== undefined) {
            adoptionData.push({ 
              name: '驳回', 
              value: this.adoptionStatusData['驳回'] || 0
            });
          }
        }
        
        // 如果没有数据，使用默认值
        if (adoptionData.length === 0) {
          adoptionData.push(
            { name: '待审核', value: 0 },
            { name: '审核通过', value: 0 },
            { name: '驳回', value: 0 }
          );
        }
        
        const colors = ['#E6A23C', '#67C23A', '#F56C6C'];
        chart.setOption(this.getChartOption(this.chartTypes.adoption, '领养申请状态统计', adoptionData, colors));
      } catch (error) {
        console.error('初始化领养申请状态图表失败:', error);
      }
    }
  }
};
</script>

<style scoped>
.admin-dashboard {
  width: 100%;
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e8ecf1 100%);
  min-height: calc(100vh - 60px);
}

/* 欢迎横幅 */
.welcome-banner {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  padding: 40px;
  margin-bottom: 20px;
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.3);
  color: white;
}

.welcome-content h1 {
  font-size: 36px;
  margin: 0 0 10px 0;
  font-weight: 700;
}

.welcome-content p {
  font-size: 18px;
  margin: 0;
  opacity: 0.95;
}

/* 卡片通用样式 */
.system-info-card,
.quick-actions-card {
  margin-bottom: 20px;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  border: none;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-icon {
  font-size: 22px;
  color: #409EFF;
}

/* 快速操作 */
.quick-actions {
  padding: 10px 0;
}

.action-item {
  text-align: center;
  padding: 20px;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #f8f9fa;
}

.action-item:hover {
  background: #e9ecef;
  transform: translateY(-4px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
}

.action-icon {
  margin-bottom: 12px;
}

.action-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

/* 系统信息样式 */
.system-info-content {
  padding: 20px 0;
}

.info-item {
  display: flex;
  align-items: center;
  padding: 24px;
  border-radius: 12px;
  transition: all 0.3s ease;
  height: 100%;
  position: relative;
  overflow: hidden;
}

.info-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: currentColor;
  opacity: 0.3;
}

.info-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.info-item-blue {
  background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
  color: #1976d2;
}

.info-item-green {
  background: linear-gradient(135deg, #e8f5e9 0%, #c8e6c9 100%);
  color: #388e3c;
}

.info-item-orange {
  background: linear-gradient(135deg, #fff3e0 0%, #ffe0b2 100%);
  color: #f57c00;
}

.info-item-purple {
  background: linear-gradient(135deg, #f3e5f5 0%, #e1bee7 100%);
  color: #7b1fa2;
}

.info-item-cyan {
  background: linear-gradient(135deg, #e0f7fa 0%, #b2ebf2 100%);
  color: #00838f;
}

.info-item-pink {
  background: linear-gradient(135deg, #fce4ec 0%, #f8bbd0 100%);
  color: #c2185b;
}

.info-item-indigo {
  background: linear-gradient(135deg, #e8eaf6 0%, #c5cae9 100%);
  color: #303f9f;
}

.info-item-teal {
  background: linear-gradient(135deg, #e0f2f1 0%, #b2dfdb 100%);
  color: #00695c;
}

.info-icon {
  font-size: 40px;
  margin-right: 16px;
  flex-shrink: 0;
}

.info-content {
  flex: 1;
}

.info-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
  font-weight: 500;
}

.info-value {
  font-size: 18px;
  color: #303133;
  font-weight: 700;
  word-break: break-all;
}

/* 图表区域 */
.charts-section {
  margin-top: 20px;
}

.chart-wrapper {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  border: none;
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.chart-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.chart-container {
  height: 400px;
  width: 100%;
}

/* 服务器详细信息样式 */
.server-detail-card {
  margin-bottom: 20px;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  border: none;
}

.server-detail-content {
  padding: 20px 0;
}

.resource-item {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
  height: 100%;
  transition: all 0.3s ease;
}

.resource-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.resource-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.resource-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.resource-icon {
  font-size: 20px;
  color: #409EFF;
}

.resource-value {
  font-size: 24px;
  font-weight: 700;
  color: #409EFF;
}

.resource-details {
  display: flex;
  justify-content: space-between;
  margin-top: 12px;
  font-size: 13px;
  color: #666;
}

.system-details {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #e4e7ed;
}

.detail-row:last-child {
  border-bottom: none;
}

.detail-label {
  font-weight: 500;
  color: #606266;
}

.detail-value {
  color: #303133;
  font-weight: 600;
}

/* JVM信息样式 */
.jvm-info {
  padding: 10px 0;
}

.jvm-item {
  background: white;
  border-radius: 8px;
  padding: 16px;
  text-align: center;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

.jvm-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.jvm-label {
  font-size: 13px;
  color: #909399;
  margin-bottom: 8px;
}

.jvm-value {
  font-size: 20px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 12px;
}

.jvm-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
  margin-top: 12px;
  font-size: 12px;
  color: #666;
}

/* 网络信息样式 */
.network-info {
  padding: 10px 0;
}

.network-item {
  background: white;
  border-radius: 8px;
  padding: 16px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

.network-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.network-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
}

.network-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
  font-size: 13px;
  color: #666;
}

.status-up {
  color: #67c23a;
  font-weight: 600;
}

.status-down {
  color: #f56c6c;
  font-weight: 600;
}

/* 磁盘信息样式 */
.disk-info {
  padding: 10px 0;
}

.disk-drive {
  background: white;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

.disk-drive:last-child {
  margin-bottom: 0;
}

.disk-drive:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.disk-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.disk-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.disk-usage {
  font-size: 18px;
  font-weight: 700;
  color: #409EFF;
}

.disk-details {
  display: flex;
  justify-content: space-between;
  margin-top: 12px;
  font-size: 13px;
  color: #666;
}

.progress-placeholder {
  margin: 16px 0;
}
</style>
